<template>
  <div class="dyTable">
    <div class="btn-options">
      <el-dropdown trigger="click" :hide-on-click="false">
        <el-button type="primary">
          Columns<i class="el-icon-arrow-down"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown" :append-to-body="false">
          <div style="max-height: 400px; overflow: auto;">
            <el-dropdown-item v-for="(item, idx) in currentCol" :key="idx">
              <el-checkbox  v-model="item.show" @change="selectColumnChange">{{item.name}}</el-checkbox>
            </el-dropdown-item>
          </div>
        </el-dropdown-menu>
      </el-dropdown>

      <el-button type="primary" :loading="entriesLoading" @click="exportEntriesClick">
        Download Entries<i class="el-icon-download"></i>
      </el-button>
      <el-button type="primary" :loading="sequenceLoading" @click="exportSequenceClick">
        Download Sequence<i class="el-icon-download"></i>
      </el-button>
    </div>
    <el-table class="table" v-loading="loading" :key="key" :data="list" border fit
              style="width: 100%"
              @selection-change="handleSelectionChange"
              :row-key="getRowKeys"
              selectRow>
      <el-table-column
          :reserve-selection="true"
          prop="id"
          type="selection"
          align="center"
          width="55">
      </el-table-column>
      <el-table-column v-for="item in columns" :key="item.field" :label="item.name" :width="item.width" align="center">
        <template v-if="item.showTips" slot="header">
          <el-popover
              placement="top-start"
              trigger="hover"
              popper-class="popView">
            <div slot="reference">
              <div style="display: flex;align-items: center;justify-content: center">
                <span>{{item.name}}</span>
                <i style="color: #fff;margin-left: 5px" class="el-icon-question"></i>
              </div>
            </div>
            <div>
              <div v-html="item.tips">
              </div>
            </div>
          </el-popover>

        </template>
        <template slot-scope="scope">
          <el-popover
              placement="top-start"
              trigger="hover"
              popper-class="popView"
              :content="scope.row[item.field]+''">
            <div slot="reference"> {{ getNotNullValue(scope.row[item.field]) }}</div>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination" v-show="total>0">
      <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[10, 20, 30, 40, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
    <a href="" target="_blank"></a>
  </div>
</template>

<script>
import {RNAType} from "@/utils/Enums"
import {parseTime} from "@/utils/tool";
import {export_txt_to_zip} from "../../vendor/Export2Zip";
import {isEmpty} from "../../utils/validate";

export default {
  name: "dyTable",
  props:['loading', 'list', 'total', 'rnaType'],
  data() {
    return {
      // 选中数组
      ids: [],
      selecSelections: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      key: 1, // table key
      currentCol: [], // 当前全部列
      columns: [], // 当前显示列
      getRowKeys(row) {
        return row.id
      },
      columns1: [
        {name: "Transcript_ID", field: "transcriptId", width: "auto", show: true},
        {name: "Viral_Genome", field: "viralGenome", width: "auto", show: true},
        {name: "Host", field: "host", width: "auto", show: true},
        {name: "Cell_Tissue", field: "cellTissue", width: "auto", show: true},
        {name: "Exon_start_Exon_end", field: "exonStartExonEnd", width: "120", show: true},
        {name: "Length", field: "length", width: "auto", show: true},
        {name: "Strand", field: "strand", width: "auto", show: true},
        {name: "Gene", field: "gene", width: "auto", show: true},
        {name: "Detection_method or source", field: "detectionMethod", width: "130", show: true},
        {name: "Class", field: "virusClass", width: "auto", show: false, showTips: true, tips: `The classification of this column comes from the software gffcompare:<br/>
m: retain intron(s), all introns matched or retained<br/>
o: other same strand overlap with reference exons<br/>
k: containment of reference (intron compatible)<br/>
j: multi-exon with at least one junction match<br/>
x: exonic overlap on the opposite strand (like o or e but on the opposite strand)<br/>
n: retained intron(s), not all introns matched/covered<br/>
i: fully contained within a reference intron<br/>
u: none of the above (unknown, intergenic)<br/>`},
        {name: "Exon_Num", field: "exonNum", width: "auto", show: false},
        {name: "Detection_coding", field: "detectionCoding", width: "auto", show: false},
        {name: "Project", field: "project", width: "auto", show: false},
        {name: "Sequence", field: "sequence", width: "auto", show: false},
        {name: "Taxid", field: "taxid", width: "auto", show: false},
        {name: "Virus_Species", field: "virusSpecies", width: "auto", show: false},
        {name: "Abbreviation", field: "abbreviation", width: "auto", show: false},
        {name: "Viral_family", field: "viralFamily", width: "auto", show: false},
        {name: "Viral_group", field: "viralGroup", width: "auto", show: false},
        {name: "TPM", field: "tpm", width: "auto", show: false},
        {name: "PMID", field: "pmid", width: "auto", show: true},
      ],
      columns2: [
        {name: "Transcript_ID", field: "transcriptId", width: "auto", show: true},
        {name: "Viral_Genome", field: "viralGenome", width: "auto", show: true},
        {name: "Host", field: "host", width: "auto", show: true},
        {name: "Cell_Tissue", field: "cellTissue", width: "auto", show: true},
        {name: "Start", field: "start", width: "auto", show: true},
        {name: "End", field: "end", width: "auto", show: true},
        {name: "Length", field: "length", width: "auto", show: true},
        {name: "Strand", field: "strand", width: "auto", show: true},
        {name: "Gene", field: "gene", width: "auto", show: true},
        {name: "Junction_read_counts", field: "junctionReadCounts", width: "110", show: true},
        {name: "Detection_method or source", field: "detectionMethod", width: "130", show: true},
        {name: "VirusCirBase_name", field: "vlncRNAbaseName", width: "120", show: false, showTips: true, tips: `This name comes from the VirusCirBase<a href="http://www.computationalbiology.cn/ViruscircBase/home.html" target="_blank">(http://www.computationalbiology.cn/ViruscircBase/home.html)</a>`},
        {name: "PMID", field: "pmid", width: "auto", show: false},
        {name: "Virus_name", field: "virusName", width: "auto", show: false},
        {name: "Taxid", field: "taxid", width: "auto", show: false},
        {name: "Virus_Species", field: "virusSpecies", width: "auto", show: false},
        {name: "Abbreviation", field: "abbreviation", width: "auto", show: false},
        {name: "Genome_length", field: "genomeLength", width: "auto", show: false},
        {name: "Viral_family", field: "viralFamily", width: "auto", show: false},
        {name: "Viral_group", field: "viralGroup", width: "auto", show: false},
        {name: "Project", field: "project", width: "auto", show: false},
        {name: "Sample", field: "sample", width: "auto", show: false},
        {name: "isoforms", field: "isoforms", width: "auto", show: false},
        {name: "Sequence", field: "sequence", width: "auto", show: false},
      ],
      columns3: [
        {name: "Transcript_ID", field: "transcriptId", width: "auto", show: true},
        {name: "Alias", field: "alias", width: "auto", show: true, showTips: true, tips: `This column name comes from miRBase`},
        {name: "Viral_Genome", field: "viralGenome", width: "auto", show: true},
        {name: "Host", field: "host", width: "auto", show: true},
        {name: "Cell_Tissue", field: "cellTissue", width: "auto", show: true},
        {name: "Start", field: "start", width: "auto", show: true},
        {name: "End", field: "end", width: "auto", show: true},
        {name: "Strand", field: "strand", width: "auto", show: true},
        {name: "Length", field: "length", width: "auto", show: true},
        {name: "RPM", field: "rpm", width: "auto", show: true},
        {name: "Detection_method or source", field: "detectionMethod", width: "130", show: true},
        {name: "type", field: "type", width: "auto", show: true},
        {name: "Sequence", field: "sequence", width: "auto", show: true},
        {name: "Pvalue", field: "pvalue", width: "auto", show: true, showTips: true, tips: `The value of Pvalue comes from the software vsRNAfinder`},
        {name: "PMID", field: "pmid", width: "auto", show: true},
        {name: "Virus_name", field: "virusName", width: "auto", show: false},
        {name: "Taxid", field: "taxid", width: "auto", show: false},
        {name: "Virus_Species", field: "virusSpecies", width: "auto", show: false},
        {name: "Abbreviation", field: "abbreviation", width: "auto", show: false},
        {name: "Viral_family", field: "viralFamily", width: "auto", show: false},
        {name: "Viral_group", field: "viralGroup", width: "auto", show: false},
        {name: "Sample", field: "sample", width: "auto", show: false},
        {name: "Project", field: "project", width: "auto", show: false},
      ],
      params: {},
      pageNum: 1,
      pageSize: 10,

      entriesLoading: false,
      sequenceLoading: false,
    }
  },
  watch: {
    rnaType: {
      handler(newVal, oldVal) {
        this.refresh()
      },
      immediate: true
    }
  },
  mounted() {
  },
  methods: {
    getNotNullValue(n) {
      if (isEmpty(n)) {
        return '-'
      }
      return n
    },
    refresh() {
      this.pageNum = 1
      this.pageSize = 10
      this.initDefCurrentCol()
      this.dealColumns()
    },
    resetSelect() {
      this.selecSelections = []
    },
    initDefCurrentCol() {
      let currentCol = []
      switch (this.rnaType) {
        case RNAType.mRNA:
          currentCol = JSON.parse(JSON.stringify(this.columns1));
          break;
        case RNAType.lncRNA:
          currentCol = JSON.parse(JSON.stringify(this.columns1));
          break;
        case RNAType.circRNA:
          currentCol = JSON.parse(JSON.stringify(this.columns2));
          break;
        case RNAType.sRNA:
          currentCol = JSON.parse(JSON.stringify(this.columns3));
          break;
      }
      this.currentCol = currentCol;
    },
    dealColumns() {
      this.columns = this.currentCol.filter(n => {
        return n.show
      })
      this.key += 1
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.pageNum = 1
      this.$emit("refreshData", this.pageNum, this.pageSize)
    },
    handleCurrentChange(val) {
      this.pageNum = val
      this.$emit("refreshData", this.pageNum, this.pageSize)
    },
    selectColumnChange() {
      this.dealColumns()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selecSelections = selection
      // this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    async exportEntriesClick() {
      if (this.selecSelections.length == 0) {
        alert("Please check and download data")
        // this.$message.warning("Please check and download data")
        return
      }
      this.entriesLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = []
        const filterVal = []
        const dataList = this.selecSelections
        this.columns.map(n => {
          tHeader.push(n.name)
          filterVal.push(n.field)
        })

        const data = this.formatJson(filterVal, dataList)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.rnaType + "_entries"
        })
        this.entriesLoading = false
      })
    },
    exportSequenceClick() {
      if (this.selecSelections.length == 0) {
        alert("Please check and download data")
        // this.$message.warning("Please check and download data")
        return
      }
      this.sequenceLoading = true
      const tHeader = [""]
      const filterVal = ["sequence"]
      const dataList = this.selecSelections
      export_txt_to_zip(tHeader, this.formatJson(filterVal, dataList), this.rnaType + "_sequence", this.rnaType + "_sequence")
      this.sequenceLoading = false
    },
    formatJson(filterVal, jsonData) {
      let str = jsonData.map(v => filterVal.map(j => {
        if (j === 'sequence') {
          return `>${v.transcriptId}\n` + v[j]
        }
        return v[j]
      }))
      return str
    },
    downloadFile(data) {
      if (!data) {
        return
      }
      let url = window.URL.createObjectURL(new Blob([data]))
      let link = document.createElement('a')
      link.style.display = 'none'
      link.href = url

      let fileName = this.rnaType + "_entries";
      link.setAttribute('download', fileName)
      document.body.appendChild(link)
      link.click()
    },
  }
}
</script>

<style lang="stylus" scoped>

.dyTable {

  .el-table /deep/ {
    .b {
      cursor pointer
    }

    .cell {
      font-weight 800
      overflow: hidden;//超出隐藏
      text-overflow: ellipsis;//超出文本设置为...
      display:-webkit-box;//将div1转换为盒子模型
      -webkit-line-clamp: 2;//设置div1的文本为2行
      -webkit-box-orient: vertical;//从顶部向底部垂直布置子元素
    }

    .el-checkbox__input.is-checked .el-checkbox__inner, .el-checkbox__input.is-indeterminate .el-checkbox__inner {
      background-color: #0064bc;
      border-color: #0064bc;
    }
    .el-checkbox__label {
      color #11427D;
    }

    th {
      background-color: #11427D;
      color: #fff
      font-size 14px
    }

    //设置图标颜色

    .el-loading-spinner .path {
      stroke: #11427D;
    }
  }

  .btn-options {
    margin-bottom 15px
    display flex
    justify-content flex-end
  }

  .el-button--primary /deep/{
    background-color: #0064bc;
    border-color: #0064bc;
    span , i{
      font-weight 700
    }
    i {
      margin-left  5px
    }
    margin-left 15px
  }

  .el-checkbox /deep/ {
    .el-checkbox__input.is-checked .el-checkbox__inner, .el-checkbox__input.is-indeterminate .el-checkbox__inner {
      background-color: #0064bc;
      border-color: #0064bc;
    }
    .el-checkbox__label {
      color #11427D;
    }
  }


  .pagination /deep/ {
    padding-top 20px
    text-align center

    .el-pagination.is-background .el-pager li:not(.disabled).active {
      background-color: #11427DFF;
      color: #FFF;
    }
  }
}

</style>
